import { BOT_CLIENT_BOT_LEFT_SUPPORT, BotLeftSupportDto } from '@boticord/bot-client'
import {
  IndexateBotsMessagePattern, IndexateCommentMessagePattern,
  IndexateResourceDto,
  IndexateServerMessagePattern,
  ResourceStatus,
} from '@boticord/resources-client'
import { Controller } from '@nestjs/common'
import { EventPattern, Payload } from '@nestjs/microservices'
import { BotsService } from '../services/bots.service'
import { ServersService } from '../services/servers.service'
import { CommentsService } from '../services/comments.service'

@Controller()
export class RpcController {
  constructor(
    private readonly bots: BotsService,
    private readonly servers: ServersService,
    private readonly comments: CommentsService,
  ) {}

  // when a user is being updated, you would usually need to reindex meilisearch data as well(developers
  // relationship is being added into meili as well)
  // that's why you would use these methods(other apps use resources-client.service.ts)
  @IndexateBotsMessagePattern()
  async indexateBots(@Payload() { id }: IndexateResourceDto) {
    await this.bots.indexate(id)
    return undefined
  }

  @IndexateServerMessagePattern()
  async indexateServers(@Payload() { id }: IndexateResourceDto) {
    await this.servers.indexate(id)
    return undefined
  }

  @IndexateCommentMessagePattern()
  async indexateComment(@Payload() { id }: IndexateResourceDto) {
    await this.comments.indexate(id)
    return undefined
  }

  @EventPattern(BOT_CLIENT_BOT_LEFT_SUPPORT)
  async botLeft(@Payload() { id }: BotLeftSupportDto) {
    const bot = await this.bots.has(id)
    if (bot) {
      await this.bots.changeStatus(id, ResourceStatus.Pending)
    }
  }
}